<template>
  <div id="pm-category-list">
    <!-- 头部区域 -->
    <el-card class="top-card">
      <i class="el-icon-s-order"></i>
      <span>商品分类列表</span>
      <el-button class="btn-add" size="mini" @click="$router.push('/pm/productCateAdd')">添加</el-button>
    </el-card>
    <!-- 列表区域 -->
    <el-table :data="listData" border v-loading="listLoading">
      <el-table-column align="center" label="编号" type="index" width="100" />
      <el-table-column align="center" prop="name" label="分类名称" />
      <el-table-column align="center" prop="parent_id" label="级别">
        <template #default="scope">
          <span>{{scope.row.parent_id === 0 ? '一级' : '二级'}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="product_unit" label="数量单位" />
      <el-table-column align="center" label="移动端显示">
        <template #default="scope">
          <el-switch v-model="scope.row.nav_status" :active-value="1" :inactive-value="0" @change="handleSwitchChange(scope.$index, scope.row, 'nav_status')" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否启用">
        <template #default="scope">
          <el-switch v-model="scope.row.show_status" :active-value="1" :inactive-value="0" @change="handleSwitchChange(scope.$index, scope.row, 'show_status')" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="排序">
        <template #default="scope">
          <span v-if="scope.row.sort === 1">升序</span>
          <span v-else type="success">降序</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="date" label="设置">
        <template #default="scope">
          <el-button @click="handleShowNextLevel(scope.row)" size="mini" :disabled="scope.row.parent_id !== 0">查看下一级</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="date" label="操作">
        <template #default="scope">
          <el-button type="warning" icon="el-icon-edit" circle @click="handleUpdate(scope.row)" size="mini"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle @click="handleDel(scope.row)" size="mini"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:currentPage="pageNum" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script>
import { reactive, toRefs, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getCategory, editCategory, delCategory } from '../../../api/categoryApi'
import { ElMessage, ElMessageBox } from 'element-plus'
export default {
  name: 'pmList',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const state = reactive({
      listData: [],
      listLoading: false, // 是否显示加载框
      parentId: 0,
      pageNum: 1,
      pageSize: 5,
      total: 0 // 总数量
    })

    onMounted(() => {
      getList()
    })

    // 请求列表数据
    const getList = () => {
      state.listLoading = true
      getCategory(state.parentId, state.pageNum, state.pageSize).then(res => {
        if (res.status && res.status === 1) {
          state.listLoading = false
          state.listData = res.data.category_list
          state.total = res.data.category_count
        } else {
          ElMessage.error(res.msg)
        }
      }).catch((err) => {
        state.listLoading = false
        console.log(err)
        ElMessage.error('请求列表数据失败!')
      })
    }

    // 处理移动端显示 和 是否启用开关是否打开
    const handleSwitchChange = (index, row, tag) => {
      if (index === -1) return
      let obj = {}
      // 处理移动端显示
      if (tag === 'nav_status') {
        obj = { id: row.id, nav_status: row.nav_status }
      } else if (tag === 'show_status') {
        // 是否启用
        obj = { id: row.id, nav_status: row.show_status }
      }
      editCategory(obj).then(res => {
        if (res.status === 1) {
          ElMessage.success(res.msg)
        } else {
          ElMessage.error(res.msg)
        }
      }).catch(err => {
        console.log(err)
        ElMessage.error(res.msg)
      })
    }

    // 跳转到编辑界面
    const handleUpdate = (row) => {
      router.push({
        path: '/pm/productCateUpdate',
        query: {
          id: row.id
        }
      })
    }

    // 处理删除
    const handleDel = (row) => {
      ElMessageBox.confirm("您确定要删除该商品分类吗?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        console.log(row)
        const result = await delCategory(row.id)
        console.log(result)
        if (result.status === 1) {
          ElMessage.success('删除商品分类成功!')
          getList()
        } else {
          ElMessage.error('删除商品分类失败!')
        }
      }).catch((err) => {
        console.log(err)
      })
    }

    // 查看下一级
    const handleShowNextLevel = (row) => {
      router.push({
        path: '/pm/productCategory',
        query: {
          parentId: row.id
        }
      })
      // 可以监视路由，当路由发生改变时，发起请求
    }

    // 监视路由的变化 current 当前活动路由对象
    watch(route, (current, prev) => {
      if (current.path === '/pm/productCategory') {
        if (current.query.parentId !== undefined) {
          state.parentId = current.query.parentId
        } else {
          state.parentId = 0
        }
        getList()
      }
    })

    // 改变每页显示条数
    const handleSizeChange = (pageSize) => {
      state.pageSize = pageSize
      getList()
    }

    // 改变当前页码
    const handleCurrentChange = (pageNum) => {
      state.pageNum = pageNum
      getList()
    }

    return {
      ...toRefs(state),
      handleSwitchChange,
      handleSizeChange,
      handleCurrentChange,
      handleDel,
      handleShowNextLevel,
      handleUpdate
    }
  }
}
</script>

<style lang="less" scoped>
.top-card {
  margin-bottom: 20px;
}
</style>